import re
from rest_framework import serializers
from The_Ten_power.utils.jwt_token import generate_jwt_token
from personal.models import User
from django_redis import get_redis_connection


class UserRegisterSerializer(serializers.ModelSerializer):
    token = serializers.CharField(read_only=True)
    sms_code = serializers.CharField(write_only=True)
    class Meta:
        model = User
        fields = ('id', 'username', 'mobile', 'token', 'avatar', 'password', 'sms_code')
        extra_kwargs = {
            'avatar': {'read_only': True},
            'username': {
                'max_length': 20,
                'min_length': 5,
                'error_messages': {
                'max_length': '密码最长20个字符',
                'min_length': '密码最短5个字符'
                }
            },
            'password': {
                'write_only': True,
                'max_length': 20,
                'min_length': 8,
                'error_messages': {
                'max_length': '密码最长20个字符',
                'min_length': '密码最短8个字符'
                }
            },
        }
    def validate(self, attrs):

        '''
        校验手机号格式是否正确&是否存在
        检查短信验证码是否失效\是否正确
        '''
        mobile = attrs.get('mobile')
        sms_code = attrs.get('sms_code')
        #校验手机号格式是否正确
        if re.match(r'^1[3-9]\d{9}$', mobile) is None:
            raise serializers.ValidationError({'error_message': '手机号格式错误'})
        #校验手机号是否被注册
        count = User.objects.filter(mobile=mobile).count()
        if count > 0:
            raise serializers.ValidationError({'error_message': '手机号已被注册'})
        # 校验短信验证码是否有效和正确
        redis_connection = get_redis_connection('sms_code')
        ret = redis_connection.get('sms_code_{}'.format(mobile))
        if ret is None:
            raise serializers.ValidationError({'error_message': '无效的短信验证码'})
        if ret.decode().lower() != sms_code.lower():
            raise serializers.ValidationError({'error_message': '短信验证码错误'})
        del attrs['sms_code']
        return attrs

    def create(self, validated_data):
        # 创建用户
        user = User.objects.create_user(**validated_data)
        user = generate_jwt_token(user)
        return user
